﻿// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Validator.Engine;
using YoProgramo.Domain.BusinessLogic.Extensions;
using YoProgramo.Domain.Core.Entities;
using YoProgramo.Domain.Core.Interfaces;
using YoProgramo.Infrastructure.Tools.NHValidator;

namespace YoProgramo.Domain.BusinessLogic.Service
{
    public class TagService : ITagService {
        private ITagRepository _tagRepository;

        public TagService(ITagRepository t)
        {
            _tagRepository = t;
        }

        public IList<ITag> GetAll()
        {
            return _tagRepository.GetAll();
        }

        public InvalidValue[] Create(ITag obj)
        {
            InvalidValue[] validatorErrors = new NHValidatorWrapper<Tag>().Validate((Tag)obj);

            if (validatorErrors.Count() < 1)
                _tagRepository.SaveOrUpdate(obj);

            return validatorErrors;
        }

        public bool Update(ITag obj)
        {
            try {
                InvalidValue[] validatorErrors = new NHValidatorWrapper<Category>().Validate((Category)obj);

                if (validatorErrors.Count() < 1)
                    _tagRepository.SaveOrUpdate(obj);

                return true;
            } catch {
                return false;
            }
        }

        public void Delete(ITag obj)
        {
            _tagRepository.Delete(obj);
        }

        public ITag GetBySlug(string slug) {
            return GetAll().FirstOrDefault(w => w.Slug == slug);
        }

        #region ITagService Members


        public IList<ITag> GetAllTagsClean() {
            return (from s in GetAll()
                    where s.StoryCount() > 0
                    select s).ToList();
        }

        #endregion
    }
}